<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Rep\FileRep;
use Illuminate\Http\Request;

class File extends Controller
{
    public function fileUpload(Request $request){
        $user_id = $request->get("user_id");
        $fileRep = new FileRep();
        set_time_limit(300);
        $file = $request->file("file");
        $file_name = $file->getClientOriginalName();
        $file_real_path = $file->getRealPath();
        $file_md5 = md5_file($file_real_path);
        $file_url  = $file->store('photograph');
        $ip = $request->getClientIp();
        $file_mime = $file->getMimeType();
        $fileInfo = $fileRep->saveFile(
            $user_id,
            $file_name,
            $file_md5,
            $file_url,
            $file->getSize(),
            $file_mime,
            $ip
        );
        return re(0,$fileInfo);
    }

    /**
     * 多文件上传
     */
    public function multipleFilesUpload(Request $request){
        $files = $request->allFiles();
        $user_id = $request->get("user_id");
        $fileRep = new FileRep();
        if(is_array($files)){
            foreach($files as $file){
                $file_name = $file->getClientOriginalName();
                $file_real_path = $file->getRealPath();
                $file_md5 = md5_file($file_real_path);
                $file_url  = $file->store('photograph');
                $ip = $request->getClientIp();
                $file_mime = $file->getMimeType();
                $fileInfo[] = $fileRep->saveFile(
                    $user_id,
                    $file_name,
                    $file_md5,
                    $file_url,
                    $file->getSize(),
                    $file_mime,
                    $ip
                );
            }

        }
        return re(0,$fileInfo);
    }

}
